/**
 * 简易的轮播图组件
 * author aty
 */


;(function(){

	var Swiper = function(options){
		if(!options.el){
			throw new Error("Error:缺少el参数");
		}
		this.options = {
			el:""
		};
		$.extend(this.options,options);
		this.initStyle();
	}

	Swiper.fn = Swiper.prototype;

	Swiper.fn.initStyle = function(){
		var self = this;
		var el = document.querySelector(this.options.el);
		var ul = el.querySelector("ul");
		var singleItem = el.offsetWidth;
			ul.className = "swiper-ul";

		var lis = $(ul).children("li");

			lis.each(function(i,ele){
				if(i==0){
					self.index = 0;
					ele.classList.add("on");
				}
				ele.style.width = 100/lis.length + "%";

				ele.onclick = function(e){
					self.options.clickItem && self.options.clickItem(e.target);
				}
			});

			ul.style.width = singleItem*lis.length + "px";

		var prevBtn = document.createElement("div");
			prevBtn.className = "prev-btn";
			prevBtn.style.display = "none";

		var nextBtn = document.createElement("div");
			nextBtn.className = "next-btn";

		prevBtn.onclick = function(e){
			self.index = self.index - 1<=0?0:self.index - 1;
			ul.style.transform = "translateX(-"+singleItem*self.index+"px)";
			self.triggerChangeEvent();
			if(self.index==0){
				prevBtn.style.display = "none";
			}else{
				prevBtn.style.display = "inline";
			}
			nextBtn.style.display = "inline";
		}

		nextBtn.onclick = function(e){
			self.index = self.index + 1>=lis.length-1?lis.length-1:self.index + 1;
			ul.style.transform = "translateX(-"+singleItem*self.index+"px)";
			self.triggerChangeEvent();

			if(self.index==lis.length-1){
				nextBtn.style.display = "none";
			}else{
				nextBtn.style.display = "inline";
			}
			prevBtn.style.display = "inline";
		}

		el.appendChild(prevBtn);
		el.appendChild(nextBtn);
	}

	Swiper.fn.triggerChangeEvent = function(){
		this.options.pageChange && this.options.pageChange(this.index);
	}
	

	window.Swiper = Swiper;

})();

